package cn.gailvlun.gll.net;

import android.support.annotation.Nullable;

import java.net.SocketTimeoutException;

import io.reactivex.CompletableObserver;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;



public abstract class NullSubscriber implements CompletableObserver {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onComplete() {
        onSuccess();
    }

    @Override
    public void onError(Throwable e) {
        onFailure(parseThrowable(e), getErrorCode(e));
    }

    private String parseThrowable(Throwable e) {
        if (e instanceof HttpException) {
            try {
                String body = ((HttpException) e).response().errorBody().string();
                Response res = GsonUtil.getGson().fromJson(body, Response.class);
                return res.getDetail();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (((HttpException) e).response().code() >= 500) {
                return "服务器内部错误";
            }
        } else if (e instanceof SocketTimeoutException) {
            return "服务器连接超时";
        }
        return "未知错误";
    }

    private int getErrorCode(Throwable e) {
        if (e instanceof HttpException) {
            return ((HttpException) e).response().code();
        }
        return 400;
    }

    protected abstract void onSuccess();
    protected abstract void onFailure(String errMsg, int code);
}
